var saveOrUpdateData = null;//临时存储的 添加修改对象 == 用于窗体间通讯问题
layui.use(['form','layer','laydate','table','laytpl','element'],function(){
    var element = layui.element;
    var laydate = layui.laydate;
    var form = layui.form,
        layer = layui.layer,
    $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;
    var currentIndex = parent.layer.getFrameIndex(window.name);//获取当前窗体索引

    if(window.parent!=null && window.parent!=undefined && window.parent.name == 'queryRecordsByPackageId'){
        console.log("设置不可编辑模式!");
        $(function(){
            $("input").attr("disabled",true);
            $("textarea").attr("disabled",true);
            $("a").addClass("layui-btn-disabled");//attr("display","none");
            $("select").attr("disabled","disabled");
            form.render('select');
            form.render('a');
        });
    }

    form.on('checkbox(selectAll)', function(data) {
        console.log("??????");
        console.log(data.elem.checked);
        $("input[name='answerType']").prop("checked", data.elem.checked);
        form.render('checkbox');
    });

    //单选
    form.on('checkbox(oneChoose)', function (data) {
        console.log("======");
        console.log(data.elem.checked);
        var i = 0;
        var j = 0;
        $("input[name='answerType']").each(function () {
            if( this.checked === true )
            {
                i++;
            }
            j++;
        });
        if( i == j )
        {
            $(".checkboxAll").prop("checked",true);
            form.render('checkbox');
        }else
        {
            $(".checkboxAll").removeAttr("checked");
            form.render('checkbox');
        }
    });

    form.on('select(skipType)', function(data) {
        console.log(data);
        if (data.value == "a") {
            $("#assignFlowDiv").css("display", "");
        }else if(data.value == "s"){
            $("#assignFlowStepDiv").css("display", "");
        }else {
            $("#assignFlowDiv").css("display", "none");
            $("#assignFlowStepDiv").css("display", "none");
        }
    });

    form.on('select(mutiSessionSkipType)', function(data) {
        if (data.value == "a") {
            $("#assignFlowDiv").css("display", "");
        }else {
            $("#assignFlowDiv").css("display", "none");
            $("#assignFlowStepDiv").css("display", "none");
        }
    });

    function arrayToString(fromName){
        var ss = "";
        if($("input:checkbox[name='"+fromName+"']:checked").length>0){
            var s = [];
            $("input:checkbox[name='"+fromName+"']:checked").each(function () {
                s.push($(this).val());
            });
            ss = s.join(",");
        }
        return ss;
    }

    //保存
    form.on('submit(add)', function(formData){
        //弹出loading
        var load = layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
        var bo = verification(formData.form,null);
        if(bo){
            formData.field["answerType"]  = arrayToString("answerType");
            var submitData = formData.field;
            var acbCbk = $("input[name='actionCodeBreak']");

            if(acbCbk!=null && acbCbk!=undefined){
                $("input[name='actionCodeBreak']").each(function (idx,elem) {
                    var elem=$(elem);
                    if(elem.attr("checked")!=undefined && elem.attr("checked")=="checked"){
                        submitData["actionCodeBreak"] = "true";
                    }else{
                        submitData["actionCodeBreak"] = "false";
                    }
                });
            }
            layer.close(load);
            saveData(submitData,load);
        }else{
            layer.close(load);
        }
    });

    function saveData(submitData,load){
        localStorage.setItem("changeDataVal","");
        if(submitData["flowId"]=="null" && submitData["packageId"]=="null"){
            //保存公共流程节点
            $.ajax({
                type: "POST",
                url:  baseUrl+'/flowConfig/saveSpeakFlowStep',
                dataType: 'json',
                data: submitData,
                success: function (data) {
                    layer.close(load);
                    if(data.code>0){
                        layer.msg("保存成功");
                        //关闭本窗体
                        setTimeout(function () {
                            // window.parent.frames.reloadTable();
                            $("#cancel").click();
                        },1000);
                    }else{
                        layer.msg("保存失败");
                    }
                },
                error: function () {
                    layer.close(load);
                    layer.msg("保存失败");
                    return ;
                }
            });
        }else{
            //保存json 的 obj 在保存流程时，在进行存储起来
            $.ajax({
                type: "POST",
                url:  baseUrl+'/flowConfig/trunFlowStepJson',
                dataType: 'json',
                data: submitData,
                success: function (data) {
                    layer.close(load);
                    console.log(data);
                    // window.parent.frames.loadFlow(data);
                    // $("#dataVal").val(JSON.stringify(data));
                    localStorage.setItem("changeDataVal",JSON.stringify(data));
                    $("#cancel").click();
                },
                error: function () {
                    layer.close(load);
                    layer.msg("保存失败");
                    return ;
                }
            });
        }
    }

    $('#cancel').on('click',function () {
        currentIndex = parent.layer.getFrameIndex(window.name);//获取当前窗体索引
        parent.layer.close(currentIndex);//执行关闭
    });

    //新增分支
    $("#add_answerType").on('click',function () {
        if(window.parent!=null && window.parent!=undefined && window.parent.name == 'queryRecordsByPackageId'){
            layer.msg("当前页只能查看详情，无法进行编辑或新增操作");
            return;
        }
        $('.todoMenu').css({'display':'none'});
        saveOrUpateCustomType(false,"0");
    });

    //编辑流程节点
    function saveOrUpateCustomType(edit,id) {
        console.log(stepId);
        $('.todoMenu').css({'display':'none'});
        var params = "?id="+id+"&flowId="+flowId+"&stepId="+stepId;
        currentIndex = layer.open({
            title : "新建分支",
            type : 2,
            content : [baseUrl+"/flowConfig/saveOrUpdateCustomerAnswerWay"+params],
            resize:true,
            maxmin:true,
            isOutAnim:true,
            scrollbar:true,
            area : ['80%','90%'],
            success : function(layero, index){
                var body = layer.getChildFrame('body', index);
                setTimeout(function(){
                    layer.tips('点击此处返回管理列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            },
            btn: ['保存', '取消'],
            yes: function (index, layero) {
                var body = layer.getChildFrame('body', index); //得到子页面层的BODY
                var button = body.find('[lay-submit]'); //获取子窗口表单提交按钮dom
                button.click();
            }
            , btn2: function (index, layero) {
                layer.close(index);
            }
        });
    }
    

    //验证表单
    function verification(form,iframeWin) {
        var config = {
            verify: {
                required: [
                    /[\S]+/
                    , '必填项不能为空'
                ]
                , phone: [
                    /^1\d{10}$|^$/
                    , '请输入正确的手机号'
                ]
                , email: [
                    /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$|^$/
                    , '邮箱格式不正确'
                ]
                , url: [
                    /(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/
                    , '链接格式不正确'
                ]
                , number: [
                    /^\d+$|^$/
                    , '只能填写数字'
                ]
                , date: [
                    /^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$|^$/
                    , '日期格式不正确'
                ]
                , identity: [
                    /(^\d{15}$)|(^\d{17}(x|X|\d)$|^$)/
                    , '请输入正确的身份证号'
                ]
            }
        };
        formElem = $(form);
        var button = $(this), verify = config.verify, stop = null
            , DANGER = 'layui-form-danger',PROMPT='required_prompt', field = {}
            , verifyElem = formElem.find('*[lay-verify-zdy]') //获取需要校验的元素
            , checkedElem = formElem.find('*[data-required]') //获取复选框
            ,rangeElem = formElem.find('*[data-range]')//获取范围判断的区间值

        //开始校验
        layui.each(verifyElem, function (_, item) {
            var othis = $(this), tips = '';
            var arr = othis.attr('lay-verify-zdy').split(',');
            for (var i in arr) {
                var ver = arr[i];
                var value = othis.val(), isFn = typeof verify[ver] === 'function';
                if(ver == 'number'&&value==''){
                    value = 0;
                }
                othis.removeClass(DANGER);
                if (verify[ver] && (isFn ? tips = verify[ver](value, item) : !verify[ver][0].test(value))) {
                    layer.msg(tips || verify[ver][1], {
                        icon: 5
                        , shift: 6
                    });
                    //非移动设备自动定位焦点
                    if (!layui.device().android && !layui.device().ios) {
                        if(item.type=='text'){
                            item.focus();
                        }else if(item.type=="select-one"){
                            $(item).next("div").find("input").focus();
                            $(item).next("div").find("input").attr("readonly");
                        }
                    }
                    othis.addClass(DANGER);
                    return stop = true;
                }
            }
        });
        if (stop) return false;
        //返回序列化表单元素， JSON 数据结构数据。
        return true;
    }

    $("#reloadForm").on('click',function () {
        form.render('checkbox');
    });

    $(document).on('click','.customMenu .editCustomType',function(){
        $('.customMenu').css({'display':'none'});
        if(currentCustomType){
            var $currentCustomType = $(currentCustomType);
            var title = $currentCustomType.find("span").first().html();
            console.log(title);
            if($("input[title='"+title+"']")){
                var currentId = $("input[title='"+title+"']").attr("id");
                console.log(currentId);
                saveOrUpateCustomType(true,currentId)
            }
        }
    });


    $(document).on('click','.customMenu .deleteCustomType',function(){
        $('.customMenu').css({'display':'none'});
        if(currentCustomType){
            var $currentCustomType = $(currentCustomType);
            var title = $currentCustomType.find("span").first().html();
            var currentId = 0;
            console.log(title);
            if($("input[title='"+title+"']")){
                var currentId = $("input[title='"+title+"']").attr("id");
                console.log(currentId);
            }
            console.log(currentId);
            layer.confirm('您确定删除此分支节点？',{icon:3, title:'提示信息'},function(index){
                var load = layer.msg('执行中，请稍候',{icon: 16,time:false,shade:0.8});
                $.ajax({
                    type: "POST",
                    url:  baseUrl+'/flowConfig/delCustomerAnswerWay?id='+currentId,
                    dataType: 'json',
                    success: function (data) {
                        layer.close(load);
                        if(data.code<=0){
                            layer.msg(data.msg);
                            layer.close(index);
                        }else{
                            if($("input[title='"+title+"']")){
                                $("input[title='"+title+"']").remove();
                            }
                            $currentCustomType.remove();
                            layer.close(index);
                        }
                    },
                    error: function () {
                        layer.close(load);
                        layer.msg("操作失败");
                        layer.close(index);
                    }
                });
            });

        }
    });

});

function loadCustomAnswerType(obj) {
    console.log(obj);
    var objId = obj.records[0].id;
    var title = obj.records[0].name;
    var editObj  =  null;
    $("#customAnswerTypeDiv").find($("input[name='answerType']")).each(function (idx,elem) {
        var elem=$(elem);
       console.log(elem.attr("id"));
       if(objId == elem.attr("id")){
           editObj = elem;
           elem.attr("title",title)
       }
    });
    if(editObj == null){
        var str = '<input  id="'+obj.records[0].id+'" lay-filter="oneChoose" type="checkbox" name="answerType" value="'+obj.records[0].id+'" title="'+title+'" lay-skin="primary">';
        console.log(str);
        $("#customAnswerTypeDiv").append(str);
    }
    $("#reloadForm").click();
}

var currentCustomType; //当前操作的自定义分支
$('#customAnswerTypeDiv').on('contextmenu',function (e) {
    e=e||event;
    target = e.target||e.srcElement;
    console.log($(target).attr("class"));
    if(target!=undefined &&  ($(target).attr("class")==undefined || ($(target).attr("class").indexOf("layui-icon-ok")==-1||$(target).attr("class").indexOf("layui-form-checkbox")==-1))){
        if($(target).parent()!=undefined  && $(target).parent().attr("class")!=undefined
            && ($(target).parent().attr("class").indexOf("layui-icon-ok")!=-1 || $(target).parent().attr("class").indexOf("layui-form-checkbox")!=-1)) {
            target = $(target).parent();
        }
    }
    currentCustomType = $(target);
    if($(target)!=undefined && ($(target).attr("class")!=undefined && ($(target).attr("class").indexOf("layui-icon-ok")!=-1 ||$(target).attr("class").indexOf("layui-form-checkbox")!=-1)))
    {
        var $menu = $('.customMenu');
        $('.todoMenu').css({'display':'none'});
        $menu.css({"display":'block','position':'fixed','zIndex':'10000'});
        $menu.css({'left':e.clientX,'top':e.clientY});
        return false;
    }else {
        return false;
    }
});

$('#customAnswerTypeDiv').on('click',function(e){
    $('.todoMenu').css({'display':'none'})
});

$('#defaultCustomerAnswerTypeDiv').on('click',function(e){
    $('.todoMenu').css({'display':'none'})
});

$('#defaultCustomerAnswerTypeDiv').on('contextmenu',function (e) {
    e=e||event;
    target = e.target||e.srcElement;
    console.log($(target).attr("class"));
    if(target!=undefined &&  ($(target).attr("class")==undefined || ($(target).attr("class").indexOf("layui-icon-ok")==-1||$(target).attr("class").indexOf("layui-form-checkbox")==-1))){
        if($(target).parent()!=undefined  && $(target).parent().attr("class")!=undefined
            && ($(target).parent().attr("class").indexOf("layui-icon-ok")!=-1 || $(target).parent().attr("class").indexOf("layui-form-checkbox")!=-1)) {
            target = $(target).parent();
        }
    }
    currentCustomType = $(target);
    if($(target)!=undefined && ($(target).attr("class")!=undefined && ($(target).attr("class").indexOf("layui-icon-ok")!=-1 ||$(target).attr("class").indexOf("layui-form-checkbox")!=-1)))
    {
        var $menu = $('.customMenu');
        $('.todoMenu').css({'display':'none'});
        $('.deleteCustomType').css({'display':'none'});
        $menu.css({"display":'block','position':'fixed','zIndex':'10000'});
        $menu.css({'left':e.clientX,'top':e.clientY});
        return false;
    }else {
        return false;
    }
});

$('#customAnswerTypeDiv').on('click',function(e){
    $('.todoMenu').css({'display':'none'})
});



/**
 * 刷新flow数据信息
 * */
function referFlows() {
    var params = "packageId="+packageId;
    $('#flowDivs').load(baseUrl+'/flowConfig/getFlowBypackageId?'+params);
}



